package top.lyc829.iot_server.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.lyc829.iot_server.bean.AccessLog;
import top.lyc829.iot_server.bean.User;
import top.lyc829.iot_server.dao.UserDao;
import top.lyc829.iot_server.service.AccessLogService;
import top.lyc829.iot_server.service.FingerService;
import top.lyc829.iot_server.service.UserService;
import top.lyc829.iot_server.utils.MqttUtil;
import top.lyc829.iot_server.utils.Result;
import top.lyc829.iot_server.utils.UserContainer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    FingerService fingerService;

    @Autowired
    AccessLogService accessLogService;

    @Resource
    private UserContainer userContainer;

    private MqttUtil mqttUtil;

    public UserServiceImpl(){
        mqttUtil = MqttUtil.build();
    }


    @Override
    public User findUserById(Integer userId) {
        return userDao.findUserById(userId);
    }

    @Override
    public User findUserByNfcId(String nfcId) {
        return userDao.findUserByNfcId(nfcId);
    }

    @Override
    public User findUserByPassword(String password) {
        return userDao.findUserByPassword(password);
    }

    @Override
    public void updateUser(User user) {
        userDao.save(user);
    }

    @Override
    public Result doLogin(User user, HttpServletResponse response) {
        User user1 = userDao.findUserById(user.getId());
        if (user1 == null) {
            return Result.fail("该用户未注册");
        } else if (user.getPassword().equals(user1.getPassword())) {
            response.addHeader("token", user.getId().toString());
            return Result.success(null);
        } else {
            return Result.fail("密码错误");
        }
    }

    @Override
    public Result getFriends() {
        List<User> users = userDao.findAll();
        users.forEach(user -> {
            user.setPassword("******");
        });
        return Result.success(users);
    }

    @Override
    public Result openDoor(Integer id) {

        User user = userDao.findUserById(id);
        if (user == null) {
            return Result.fail("该用户不存在");
        }

        //TODO:发送mqtt开门消息
        userContainer.setUser(user);
        mqttUtil.publish("/server/open_door",user.getName());

        AccessLog accessLog = new AccessLog();
        accessLog.setUserId(id);
        accessLog.setType(1);
        accessLog.setTypeId("-1");
        accessLog.setState(1);
        accessLog.setTime(new Date());

        accessLogService.add(id, 1, "-1", 1);

        return Result.success();
    }


}
